from django.contrib import admin
from django.contrib.auth.models import User

from lesson.models import Lesson, Lesson_class, Subject

class MyModelAdmin(admin.ModelAdmin):
    # exclude = ['teacher', ]
    # preserve_filters = True
    # readonly_fields = ['teacher', ]


    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(teacher=request.user)

    # def formfield_for_dbfield(self, db_field, request, **kwargs):
    #     field = super().formfield_for_dbfield(db_field, request, **kwargs)
    #     if db_field.name == 'teacher' and request.user.is_superuser is False:
    #         field.initial = request.user
    #         field.limit_choices_to = {'username': request.user}
    #         # field.disabled = True
    #     return field

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        field = super().formfield_for_foreignkey(db_field, request, **kwargs)
        if db_field.name == "teacher":
            field.initial = request.user
            field.limit_choices_to = {'username': request.user}
            kwargs["queryset"] = User.objects.filter(id=request.user.id)
        return field
        # return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    # def save_model(self, request, obj, form, change):
    #     if request.user.is_superuser:
    #         pass
    #     else:
    #         obj.teacher = request.user
    #     obj.save()

    # def get_form(self, request, obj=None, **kwargs):
    #     if request.user.is_superuser is False:
    #         self.exclude = ("teacher",)
    #     form = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
    #     return form


# Register your models here.o
admin.site.register(Lesson)
admin.site.register(Lesson_class)
admin.site.register(Subject, MyModelAdmin)